﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;

namespace Bookworm.Controls
{
    public class VistaGlassHelper
    {
        [DllImport("DwmApi.dll")]
        public static extern int DwmExtendFrameIntoClientArea(
            IntPtr hwnd,
            ref Margins pMarInset);

        [StructLayout(LayoutKind.Sequential)]
        public struct Margins
        {
            public int CxLeftWidth;
            public int CxRightWidth;
            public int CyTopHeight;
            public int CyBottomHeight;
        }

        public static Margins GetDpiAdjustedMargins(IntPtr windowHandle,int left, int right, int top, int bottom)
        {
            // Get the system DPI.
            System.Drawing.Graphics desktop = System.Drawing.Graphics.FromHwnd(windowHandle);
            float desktopDpiX = desktop.DpiX;
            //float desktopDpiY = desktop.DpiY;
            // Set the margins.
            var margins = new Margins
                              {
                                  CxLeftWidth = Convert.ToInt32(left*(desktopDpiX/96)),
                                  CxRightWidth = Convert.ToInt32(right*(desktopDpiX/96)),
                                  CyTopHeight = Convert.ToInt32(top*(desktopDpiX/96)),
                                  CyBottomHeight = Convert.ToInt32(bottom*(desktopDpiX/96))
                              };
            return margins;
        }
        public static void ExtendGlass(Window win, int left, int right, int top, int bottom)
        {
            // Obtain the window handle for WPF application
            IntPtr windowHandle = new WindowInteropHelper(win).Handle;
            HwndSource mainWindowSrc = HwndSource.FromHwnd(windowHandle);
            if (mainWindowSrc != null) 
                mainWindowSrc.CompositionTarget.BackgroundColor = Color.FromArgb(0, 0, 0, 0);
            Margins margins = GetDpiAdjustedMargins(
                windowHandle, left, right, top, bottom);
            // Extend the glass frame.
            int returnVal = DwmExtendFrameIntoClientArea(windowHandle, ref margins);
            if (returnVal < 0)
            {
                throw new NotSupportedException("Operation failed.");
            }
        }
    }
}